//
//  KindViewConroller.m
//  MoneyLog
//
//  Created by wicresoft on 6/22/11.
//  Copyright 2011 wicresoft. All rights reserved.
//

#import "KindViewConroller.h"
#import "KindWrapper.h"
#import "TypeListViewController.h"

extern NSString *kSectionTitleKey;
extern NSString *kRowViewKey;
extern NSString *kRowTextKey;
extern NSString *kRowAccessTypeKey;

@implementation KindViewConroller
@synthesize titleString;
@synthesize kind;
@synthesize dataSourceArray;

@synthesize actionSheet;
@synthesize pickerDataSource;
@synthesize _pickerView;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [titleString release];
    [kind release];
    [dataSourceArray release];
    [typeListViewController release];
    
    [kindNameTextField release];
    [typeLabel release];
    [useTimesLabel release];
    [markSwitch release];
    
    [actionSheet release];
    [pickerDataSource release];
    [_pickerView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    //self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.title = titleString;
    
    kindNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(100,10,160, 30)];
    kindNameTextField.borderStyle = UITextBorderStyleNone;
    kindNameTextField.textColor = [UIColor blackColor];
    kindNameTextField.textAlignment = UITextAlignmentRight;
    kindNameTextField.font = [UIFont systemFontOfSize:17.0]; 
    kindNameTextField.backgroundColor = [UIColor whiteColor];
    kindNameTextField.autocorrectionType = UITextAutocorrectionTypeNo;	 
    kindNameTextField.keyboardType = UIKeyboardTypeDefault;	 
    kindNameTextField.returnKeyType = UIReturnKeyDefault;
    kindNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;	
    kindNameTextField.text = kind.kindName;
    kindNameTextField.delegate = self;	   
    
    typeLabel =[[UILabel alloc] initWithFrame:CGRectMake(100, 6, 160, 30)];
    typeLabel.textAlignment =UITextAlignmentRight;
    typeLabel.text = kind.type;
    
    useTimesLabel =[[UILabel alloc] initWithFrame:CGRectMake(100, 6, 160, 30)];
    useTimesLabel.textAlignment =UITextAlignmentRight;
    useTimesLabel.text =[NSString stringWithFormat:@"%d",kind.useTimes];
    
    markSwitch =[[UISwitch alloc] initWithFrame:CGRectMake(180, 6, 100, 30)];
    markSwitch.on = kind.mark;
    
    self.dataSourceArray = [NSMutableArray arrayWithObjects:
                            [NSDictionary dictionaryWithObjectsAndKeys:
                             @"类型名",kRowTextKey,
                             kindNameTextField,kRowViewKey,
                             [NSNumber numberWithInt:UITableViewCellAccessoryNone],kRowAccessTypeKey,nil],
                            
                            [NSDictionary dictionaryWithObjectsAndKeys:
                             @"分类",kRowTextKey,
                             typeLabel,kRowViewKey,
                             [NSNumber numberWithInt:UITableViewCellAccessoryNone],kRowAccessTypeKey,nil],
                            
                            [NSDictionary dictionaryWithObjectsAndKeys:
                             @"使用次数",kRowTextKey,
                             useTimesLabel,kRowViewKey,
                             [NSNumber numberWithInt:UITableViewCellAccessoryNone],kRowAccessTypeKey,nil],
                            
                            [NSDictionary dictionaryWithObjectsAndKeys:
                             @"收藏",kRowTextKey,
                             markSwitch,kRowViewKey,
                             [NSNumber numberWithInt:UITableViewCellAccessoryNone],kRowAccessTypeKey,nil],

                            nil];
    
    //ActionSheet
    actionSheet = [[UIActionSheet alloc] 
                   initWithTitle:@""
                   delegate:self 
                   cancelButtonTitle:nil 
                   destructiveButtonTitle:nil
                   otherButtonTitles:nil]; 
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    
    //PickerView
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
    _pickerView.showsSelectionIndicator = YES;						 
    _pickerView.delegate = self;
    _pickerView.dataSource = self; 
    _pickerView.tag=0xF001;
    
    self.pickerDataSource =[NSMutableArray arrayWithObjects:@"支出",@"收入", nil];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.dataSourceArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    cell.textLabel.text = [[self.dataSourceArray objectAtIndex:indexPath.row] objectForKey:kRowTextKey];
    cell.accessoryType = [[[self.dataSourceArray objectAtIndex:indexPath.row] objectForKey:kRowAccessTypeKey] intValue];
    [cell.contentView addSubview:[[self.dataSourceArray objectAtIndex:indexPath.row] objectForKey:kRowViewKey]];
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    [kindNameTextField resignFirstResponder];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row ==1) {
        [self._pickerView reloadAllComponents];
        
        //工具栏
        CGRect appRect = [[UIScreen mainScreen] applicationFrame];
        UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, appRect.size.width, 44)];
        toolBar.barStyle = UIBarStyleBlack;
        toolBar.translucent =YES;
        [toolBar sizeToFit];
        
        NSMutableArray *barItems = [[NSMutableArray alloc] init]; 
        
        UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] 
                                         initWithBarButtonSystemItem:UIBarButtonSystemItemCancel 
                                         target:self 
                                         action:@selector(pickerCancel)];
        [barItems addObject:cancelButton];
        [cancelButton release];
        
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] 
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                                      target:self action:nil];
        [barItems addObject:flexSpace];
        
        //标题
        UIBarButtonItem *titleButton = [[UIBarButtonItem alloc] init];
        titleButton.style = UIBarButtonItemStylePlain;
        titleButton.title = @"选择分类";
        [barItems addObject:titleButton];
        [titleButton release];
        
        [barItems addObject:flexSpace];
        [flexSpace release];
        
        //确定按钮
        UIBarButtonItem *buttonDone = [[UIBarButtonItem alloc] 
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                       target:self 
                                       action:@selector(pickerDone)];
        [barItems addObject:buttonDone]; 
        [buttonDone release];
        
        [toolBar setItems:barItems animated:YES];
        [barItems release];
        
        [actionSheet addSubview:toolBar];
        [actionSheet addSubview:_pickerView];    
        [actionSheet showInView:[UIApplication sharedApplication].keyWindow];
        [actionSheet setBounds:CGRectMake(0, 0, appRect.size.width, appRect.size.height)];
        
        [toolBar release];
    }
}

#pragma mark - * UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	// the user pressed the "Done" button, so dismiss the keyboard
	[textField resignFirstResponder]; 
    kind.kindName = textField.text;
	return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    if ([textField.text length] != 0) {
        kind.kindName = textField.text;
    }
    else {
        
    }
    
    return YES;
}

#pragma mark - * UIPickerViewDelegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	if (pickerView.tag == 0xF001)
	{
        typeLabel.text = [self.pickerDataSource objectAtIndex: row];
	}
    
}

#pragma mark - * UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	NSString *content=@"";
	
	// note: custom picker doesn't care about titles, it uses custom views
	if (pickerView.tag == 0xF001)
	{
		if (component == 0)
		{
			content = [self.pickerDataSource objectAtIndex: row];
        }
	}
	
	return content;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 0.0;
	
	if (component == 0)
		componentWidth = 280.0;	// first column size is wider to hold names
	//else
	//	componentWidth = 40.0;	// second column is narrower to show numbers
	
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 40.0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [pickerDataSource count]; 
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}

#pragma mark - * Action sheet delegate method.

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0)
    {
        exit(0);
    }
}

#pragma mark - * action

-(void)pickerDone{
    kind.type = [self.pickerDataSource objectAtIndex: [_pickerView selectedRowInComponent:0]];
    
    
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

-(void)pickerCancel {
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}


@end
